package models

import (
	"gitee.com/zhongguo168a/go-nodex/dbx"
	"gitee.com/zhongguo168a/go-nodex/dbx/mongox"
	"gitee.com/zhongguo168a/gocodes/datax/jsonmap"
	"gitee.com/zhongguo168a/gocodes/datax/listx/constraints"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

const TableDatabase = "database"

func init() {
	dbx.RegisterTable(&mongox.Table{
		Name:       TableDatabase,
		Database:   NODE_DBNAME,
		PrimaryKey: "_id",
		Indexs: map[int]*mongo.IndexModel{
			0: {
				Keys: bson.D{
					{Key: "_id", Value: mongox.IndexSortOrderAscende},
				},
			},
		},
	})
}

type DatabaseKind int

const (
	DatabaseKind_Mongo DatabaseKind = iota
	DatabaseKind_Mysql
)

func NewDatabaseConfig() (obj *DatabaseConfig) {
	obj = &DatabaseConfig{}
	return
}

type DatabaseConfig struct {
	Id string `alias:"_id"`
	// 数据库的名字，全局唯一
	Name string
	// 数据库的地址
	Addr string
	// 数据库的类型
	Kind       DatabaseKind
	UpdateTime int
	CreateIime int
}

func (d *DatabaseConfig) DBTable() string {
	return TableDatabase
}

func (d *DatabaseConfig) DBIdent() string {
	return d.Id
}

func (d *DatabaseConfig) DBQuery() map[string]interface{} {
	return map[string]interface{}{
		"_id": d.Id,
	}
}

func (d *DatabaseConfig) DBObject() map[string]interface{} {
	lastChange := map[string]interface{}{}
	err := jsonmap.StructToMap(d, lastChange)
	if err != nil {
		panic(errorx.Wrap(err, "jsonmap struct to map"))
	}
	return lastChange
}

func (d *DatabaseConfig) DBInit() (err error) {
	return
}

func FindDatabaseConfigList() (list *DatabaseConfigList, err error) {
	result, err := mongox.NewRequestByName(TableDatabase).
		WithCreator(func() interface{} {
			return NewDatabaseConfig()
		}).
		WithItemHandler(mongox.JSONItemHandler()).
		Find(map[string]interface{}{})
	if err != nil {
		err = errorx.Wrap(err, "read database configs")
		return
	}
	list = NewDatabaseConfigList()
	for _, val := range result {
		list.Push(val.(*DatabaseConfig))
	}
	return
}

func NewDatabaseConfigList() (obj *DatabaseConfigList) {
	obj = &DatabaseConfigList{}
	return
}

type DatabaseConfigList struct {
	constraints.List[*DatabaseConfig]
}
